package com.autumn.platform.core.crypto;

import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;

import org.springframework.util.Base64Utils;

/* package */ class CryptoUtils {

    protected static final SecureRandom random = new SecureRandom();

    /**
     * 获取Provider对象：注意单例
     * 
     * @return
     */
    protected static Provider getProvider() {
        return null;//provider;
    }

    /**
     * 字节转换为字符串
     * 
     * @param data
     * @return
     */
    protected static String encodeToString(byte[] data) {
        return Base64Utils.encodeToString(data);
    }

    /**
     * 字符串转换为字节
     * 
     * @param src
     * @return
     */
    protected static byte[] decodeFromString(String src) {
        return Base64Utils.decodeFromString(src);
    }

    /**
     * 获取Cipher对象
     * 
     * @param keyAlgorithm
     * @return
     */
    protected static Cipher getCipher(String keyAlgorithm) {
        try {
            Provider provider = getProvider();
            Cipher cipher = null;
            if (null == provider) {
                cipher = Cipher.getInstance(keyAlgorithm);
            } else {
                cipher = Cipher.getInstance(keyAlgorithm, provider);
            }
            return cipher;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (NoSuchPaddingException e) {
            throw new RuntimeException(e);
        }
    }
}
